import { useEffect, useRef, useState } from "react";
import FxyhsjglApi from "../../../../../utils/apis/FxyhsjglApi";
import { Card, Space, Button, Popconfirm, Upload, Tree, Input, Dropdown ,message} from "antd";
import ScrollTable from "../../../../common/ScrollTable";
import { useHistory } from "react-router-dom/cjs/react-router-dom.min";
import { UpCircleOutlined } from "@ant-design/icons";
import { dataToFeature } from "../../../../../utils/helper/mapHelper";
import FetchHelper from "../../../../../utils/helper/fetch-helper";

export default function Fxyhsjgl() {
    const [fxsjDatas, setFxsjDatas] = useState();
    const [loading, setLoading] = useState();
    const [total, setTotal] = useState();
    const rootRef = useRef();
    const history = useHistory();
    const [category, setCategory] = useState();
    const [category2, setCategory2] = useState();
    const [category3, setCategory3] = useState();
    const [params, setParams] = useState({
        pageSize: 10,
        pageNum: 1
    });
    const [node, setNode] = useState(null);
    const [selectedNode, setSelectedNode] = useState(null)
    // const yhlb=selectedNode?.key
    const [value, setValue] = useState()
    useEffect(() => {
        setLoading(true);
        let promise;
        if (selectedNode && selectedNode?.children) {
            promise = FxyhsjglApi.list(params)
        } else {
            promise = FxyhsjglApi.list({...params,yhlb:selectedNode?.key})
        }
        console.log('fxsjDatas', params)
        promise.then(resp => {
            if (value) {
                const filterData = resp?.rows.filter(item => item?.yhmc.includes(value))
                setFxsjDatas(filterData)
            } else {
                setFxsjDatas(resp.rows);
            }

            setTotal(resp.total);
        }).finally(() => {
            setLoading(false)
        })
    }, [selectedNode, value,params])
    // console.log('fxsjDatas',fxsjDatas)
    //console.log('selectedNode',selectedNode)

    useEffect(() => {
        FxyhsjglApi.getFxyhCategroy().then(datas => {
            setCategory(datas)
        })
    }, [])
    useEffect(() => {
        FxyhsjglApi.getFxyhCategroy2().then(datas => {
            setCategory2(datas)
        })
    }, [])
    useEffect(() => {
        FxyhsjglApi.getFxyhCategroy3().then(datas => {

            setCategory3(datas)
        })
    }, [])

    const props = {
        name: 'file',
        action: '/admin-api/ybyj/yhsj/import',
        headers: {
            authorization: 'authorization-text',
        },
        beforeUpload(file) {
            const isValidFormat = file.type === 'application/vnd.ms-excel';
            

            if (!isValidFormat) {
                message.error('只能上传 .xls 格式的文件!');
            }
          

            return isValidFormat 
        },
        onChange(info) {
            //sconsole.log('node',info)
            if (info.file.status === 'done') {
                message.success(`${info.file.name} 文件上传成功`);
            } else if (info.file.status === 'error') {
                message.error(`${info.file.name} 文件上传失败`);
                alert(`数据表格可能与本数据表不一致，最好先导出一份数据，使用其模板写入数据后在进行上传`)
            }
        },
    }
    const fxyhsjglHandleLook = (record) => {
        history.push(`/manager/fxyhLook/${record.id}`)
    }
    const fxyhsjglHandleEdit = (record) => {
        history.push(`/manager/fxyhEdit/${record.id}`)
    }
    const fxyhsjglHandleDelete = (record) => {
        const newcztData = fxsjDatas.filter(function (arr) {
            return arr.id !== record.id
        })

        FetchHelper.deleteJson(`/admin-api/ybyj/yhsj/` + record.id).then(() => alert('删除成功')).catch(error => alert("删除失败") + error)


        setFxsjDatas(newcztData)
    }
    const [selectedKeys, setSelectedKey] = useState('风险隐患分类')
    const onSearch = (value) => {
        setSelectedKey('风险隐患分类')
        setValue(value)
        
        setParams(params => {
            // console.log(params)
            return {

                ...params,
                yhmc: value,
                pageNum: 1
            }
        });
    }
    const items = category3

    const [keyPath, setKeyPath] = useState();
    const fxyhAddDatas = (keyPath) => {

        history.push(`/manager/fxyhAdd/${keyPath}`)
    }

   
    const handleJudge = (selectedKeys, keyPath) => {
        if (selectedKeys?.children?.length > 1 || selectedKeys === '风险隐患分类') {
            window.alert('请选择小类')
        }
        else {
            const keyPath = selectedKeys?.key
            fxyhAddDatas(keyPath)
        }
    }
    //console.log('selectedKeys',selectedKeys)
    return <div className="layout-h h100">
        <Card size='small' className='h100' style={{
            width: 240,
            marginRight: 12,
            overflowX: "auto",
            overflowY: "auto"

        }}
        // title={"风险隐患分类"}
        >
            {category && <Tree className='categray-tree'
                treeData={category} blockNode
                defaultExpandAll
                rootStyle={{ color: '#aaa' }}
                onSelect={(selectedKeys, { node }) => {
                    setNode(node)
                    setSelectedNode(node)
                    setSelectedKey(node)//控制没选中小类就弹提示框的状态
                    //selectedKeys为所选中的节点名，node为所选中节点 node.children可以判断是否有子节点
                    setSelectedKey(selectedKeys?.[0])
                    console.log(selectedKeys)
                    console.log(node)
                    console.log(selectedKeys[0])
                    const p = {}
                    if (node.children) {
                        p.cztMiddle = selectedKeys?.[0]
                    } else {
                        p.cztSmall = selectedKeys?.[0]
                    }

                    setParams(params => {
                        return {
                            pageSize: params.pageSize,
                            pageNum: 1,
                            ...p
                        }
                    })

                }}
                defaultSelectedKeys={selectedKeys}
            />}

        </Card>
        <Card size="small" className="h100 fill w0" style={{
            position: "relative",
        }}
            bodyStyle={{
                display: "flex",
                flexDirection: "column",
                height: "100%"
            }}
        >
            <div style={{
                marginBottom: 12,
                display: 'flex',
                alignItems: "center",
                justifyContent: "space-between"
            }}>
                {/* 新增 */}
                <Space>
                    <>
                        <Button onClick={() => handleJudge(selectedKeys, keyPath)}>新增</Button>
                        <Upload {...props}>
                            <Button  icon={<UpCircleOutlined />}>数据导入</Button>
                        </Upload>
                        {/* <Button disabled={selectedKeys==='风险隐患分类'} type="primary" key="download" onClick={() => {
                            fetch(`/admin-api/ybyj/yhsj/exportLike?columnNames=${node?.tag}&key=${node.key}`, {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json;charset=UTF-8'
                                }
                            }).then(response => response.blob()).then(blob => {
                                const a = document.createElement("a");
                                a.download = "data.xls";
                                a.href = URL.createObjectURL(blob);
                                a.click();
                            }).catch(error => console.log(error))
                        }}>数据导出</Button> */}
                    </>
                </Space>
                {/* 查找 */}
                <div>
                    <Input.Search placeholder='输入名称查找'
                        allowClear
                        enterButton={true}
                        onSearch={onSearch}
                    />
                </div>
            </div>
            <div ref={rootRef} className="fill h0">
                {<ScrollTable style={{

                }}
                    loading={loading}
                    parentNode={rootRef.current}
                    size='small'
                    bordered
                    dataSource={fxsjDatas}
                    // scroll={{
                    //     x: 320 + _.sumBy(tableCols, 'width'),
                    // }}
                    columns={[
                        {
                            title: '隐患名称',
                            dataIndex: 'yhmc',
                            fixed: 'left',
                            width: 160

                        },
                        {
                            title: '隐患类型',
                            dataIndex: 'yhlx',
                            fixed: 'left',
                            width: 160

                        }, {
                            title: '隐患类别',
                            dataIndex: 'yhlb',

                            width: 160

                        },
                        {
                            title: '经度',
                            dataIndex: 'jd',

                            width: 160

                        }, {
                            title: '维度',
                            dataIndex: 'wd',

                            width: 160

                        },
                        {
                            title: '责任人',
                            dataIndex: 'zrr',

                            width: 160

                        },
                        {
                            title: '检测人姓名',
                            dataIndex: 'jcrxm',
                            width: 160

                        }, {
                            title: '监测人电话',
                            dataIndex: 'jcrdh',

                            width: 160

                        }, {
                            title: '威胁财产',
                            dataIndex: 'wxcc',

                            width: 160

                        }, {
                            title: '威胁对象',
                            dataIndex: 'wxdx',

                            width: 160

                        }, {
                            title: '威胁人数',
                            dataIndex: 'wxrs',

                            width: 160

                        }, {
                            title: '隐患点编号',
                            dataIndex: 'yhdbh',

                            width: 160

                        }, {
                            title: '隐患点发现时间',
                            dataIndex: 'yhdfxsj',

                            width: 160

                        }, {
                            title: '隐患点发现时间',
                            dataIndex: 'yhdfxsj',

                            width: 160

                        },
                        {
                            title: '操作',
                            key: 'caozuo',
                            width: 260,
                            render: (text, record) => {
                                return <Space size="middle">
                                    <Button onClick={e => { fxyhsjglHandleLook(record) }}>查看</Button>

                                    <Button onClick={e => { fxyhsjglHandleEdit(record) }}>编辑</Button>
                                    <Popconfirm title="确定删除吗?" onConfirm={e => fxyhsjglHandleDelete(record)}>
                                        {/* <Button onComfir={e => { deleteHandle(record) }}>删除</Button> */}
                                        <Button>删除</Button>
                                    </Popconfirm>
                                </Space>

                            }
                        }


                    ].map(item => {
                        return {
                            ...item,

                        }
                    })}
                    pagination={{
                        current: params.pageNum,
                        pageSize: params.pageSize,
                        total,

                    }}
                    onChange={({ current }) => {
                        setParams(params => {
                            return {
                                ...params,
                                pageNum: current
                            }
                        })
                    }}

                />}
            </div>

        </Card>
    </div>
}